# 主路由模块
from flask import Blueprint, render_template, jsonify, request
from services.trading import TradingService
from services.analysis import AnalysisService
from services.risk import RiskService
from services.statistics import StatisticsService
from flask_sqlalchemy import SQLAlchemy
import os

db = SQLAlchemy()

main = Blueprint('main', __name__)

# 初始化服务
# 使用一个标志来确保初始化只执行一次
services_initialized = False

@main.before_app_request
def init_services():
    global services_initialized, trading_service, analysis_service, risk_service, statistics_service
    
    if not services_initialized:
        # 这里应该从应用上下文中获取数据库会话
        # 为简化示例，我们这里使用全局变量
        
        # 模拟数据库会话
        db_session = None
        
        # 初始化服务
        risk_service = RiskService(db_session)
        trading_service = TradingService(db_session, risk_service)
        analysis_service = AnalysisService(db_session, None)  # 这里应该传入股票API实例
        statistics_service = StatisticsService(db_session)
        
        services_initialized = True

# 首页路由
@main.route('/')
def index():
    return render_template('index.html')

# 交易相关路由
@main.route('/api/trade/buy', methods=['POST'])
def buy_stock():
    data = request.json
    user_id = data.get('user_id')
    stock_code = data.get('stock_code')
    price = data.get('price')
    quantity = data.get('quantity')
    
    result = trading_service.buy_stock(user_id, stock_code, price, quantity)
    return jsonify(result)

@main.route('/api/trade/sell', methods=['POST'])
def sell_stock():
    data = request.json
    user_id = data.get('user_id')
    stock_code = data.get('stock_code')
    price = data.get('price')
    quantity = data.get('quantity')
    
    result = trading_service.sell_stock(user_id, stock_code, price, quantity)
    return jsonify(result)

# 分析相关路由
@main.route('/api/analysis/<stock_code>')
def get_analysis(stock_code):
    result = analysis_service.get_stock_analysis(stock_code)
    return jsonify(result)

@main.route('/api/analysis/predict/<stock_code>')
def predict_trend(stock_code):
    result = analysis_service.predict_stock_trend(stock_code)
    return jsonify(result)

# 统计相关路由
@main.route('/api/statistics/trading/<user_id>')
def get_trading_stats(user_id):
    period = request.args.get('period', 'week')
    result = statistics_service.get_trading_statistics(user_id, period)
    return jsonify(result)

@main.route('/api/statistics/portfolio/<user_id>')
def get_portfolio_stats(user_id):
    result = statistics_service.get_portfolio_stats(user_id)
    return jsonify(result)